//
//  DevSocketManage.m
//  RuiHeApp
//
//  Created by Jun on 2022/11/30.
//

#import "DevSocketManage.h"
#import "GCDAsyncSocket.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <SystemConfiguration/SystemConfiguration.h>


@interface  DevSocketManage()<GCDAsyncSocketDelegate>

// 客户端socket
@property (strong, nonatomic) GCDAsyncSocket *clientSocket;

 // 计时器
@property (nonatomic, strong) NSTimer *connectTimer;

@property (nonatomic, copy) void(^resultBlock)(BOOL isConnect);

@end

@implementation DevSocketManage


+ (DevSocketManage *)shareSocketManage{
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}


- (instancetype)init{
    self = [super init];
    if (self) {
    }
    return self;
}

// 添加计时器
- (void)addTimer
{
     // 长连接定时器
    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
     // 把定时器添加到当前运行循环,并且调为通用模式
    [[NSRunLoop currentRunLoop] addTimer:self.connectTimer forMode:NSRunLoopCommonModes];
}


// 开始连接
- (void)connectToHost:(NSString *)host  onPort:(NSInteger)port result:(nonnull void (^)(BOOL isConnect))block
{
    // 链接服务器
    self.resultBlock = block;
    if (self.socketState == DevSocketStateDisconnect){
        self.socketState = DevSocketStateConnecting;
        self.clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
        NSLog(@"开始连接%@ host:%@  port:%zd",self.clientSocket,host,port);
        NSError *error = nil;
        BOOL connectResult = [self.clientSocket connectToHost:host onPort:port viaInterface:nil withTimeout:30 error:&error];
        if(connectResult){
            if (self.resultBlock) {
                self.resultBlock(connectResult);
            }
            NSLog(@"---->正常连接");
        }else{
            if (self.resultBlock) {
                self.resultBlock(connectResult);
            }
            self.socketState = DevSocketStateDisconnect;
            NSLog(@"---->连接失败:%@",error);
        }
        if(error){
            NSLog(@"-------->连接失败:%@",error);
        }else{
//            NSLog(@"-------->连接成功");
        }
        
    }else{
        if (self.resultBlock) {
            self.resultBlock(YES);
        }
    }
}

//断开连接
- (void)disconnect{
    [self.clientSocket disconnect];
}

// 发送数据
- (void)sendMessage:(NSString *)message
{
    NSLog(@"---->发送消息:%@",message);
    NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
    // withTimeout -1 : 无穷大,一直等
    // tag : 消息标记
    [self.clientSocket writeData:data withTimeout:60 tag:0];
}

#pragma mark - GCDAsyncSocketDelegate

/**
 连接主机对应端口号

 @param sock 客户端socket
 @param host 主机
 @param port 端口号
 */
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
//    NSLog(@"连接主机对应端口%@", sock);
//    [self showMessageWithStr:@"connection successful"];
    //[self showMessageWithStr:[NSString stringWithFormat:@"IP: %@-------port: %d", host,port]];
    
    // 连接成功开启定时器
    [self addTimer];
    // 连接后,可读取服务器端的数据
    [self.clientSocket readDataWithTimeout:-1 tag:0];
    self.socketState = DevSocketStateConnected;
    if ([self.delegate respondsToSelector:@selector(DevSocket:didConnectToHost:port:)]) {
        [self.delegate DevSocket:sock didConnectToHost:host port:port];
    }
    
}

// 心跳连接
- (void)longConnectToSocket
{
    // 发送固定格式的数据,指令@"longConnect"
    float version = [[UIDevice currentDevice] systemVersion].floatValue;
    NSString *longConnect = [NSString stringWithFormat:@"h_pack:%f",version];
    NSData  *data = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
    //[self.clientSocket writeData:data withTimeout:-1 tag:0];
}

/**
 读取数据

 @param sock 客户端socket
 @param data 读取到的数据
 @param tag 当前读取的标记
 */
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    if([text isEqualToString:@"200"]){
        [QMUITips showSucceed:@"netword config success"];
        [[NSNotificationCenter defaultCenter]postNotificationName:NetwordConfigSuccessNotification object:nil];
    }
    //[self showMessageWithStr:text];
    if (text) {
        //[self showMessageWithStr:@"setting network successful!"];
        NSLog(@"----%@",text);
        /*host:www.zlgcloud.com,path:/v1/
         login,port:8143,type:HE BAT,key:1ff6d9a0-1705-11ed-b56c-
         a58cf89ccf09,id:M10RPO1202303240014    ,period:60,
         */
        /*NSArray *array = [text componentsSeparatedByString:@","];
        if(array.count>6&&[[array firstObject] isEqualToString:@"host:www.zlgcloud.com"]){
            NSString *str = [array objectAtIndex:5];
            NSArray *devIds = [str componentsSeparatedByString:@":"];
            if(devIds.count>1){
                NSString *devId = [devIds lastObject];
                BOOL isOK = [devId isOnlyAlphaAndNumeric];
                if(!isOK){
                    for (NSInteger i = 0; i<devId.length; i++) {
                        NSString *one_str = [devId substringWithRange:NSMakeRange(i, 1)];
                        if(![one_str isOnlyAlphaAndNumeric]){
                            isOK = NO;
                            devId = [devId substringWithRange:NSMakeRange(0, i)];
                            break;
                        }
                    };
                }
                if(devId.length>0){
                    [DevSocketManage shareSocketManage].isNeedUpdate = isOK?NO:YES;
                    [DevSocketManage shareSocketManage].devId = [NSString removalSpecialCharacters:devId];
                }
            }
        }*/
    }
    // 读取到服务器数据值后,能再次读取
    [self.clientSocket readDataWithTimeout:-1 tag:0];
    if([self.delegate respondsToSelector:@selector(DevSocket:didReceiveData:withTag:)]){
        
        [self.delegate DevSocket:sock didReceiveData:text withTag:tag];
    }
}

// 信息展示
- (void)showMessageWithStr:(NSString *)str
{
    [ProgressHUDManage showInfo:str];
    //self.showMessageTextV.text = [self.showMessageTextV.text stringByAppendingFormat:@"%@\n", str];
}

/**
 客户端socket断开

 @param sock 客户端socket
 @param err 错误描述
 */
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"断开的sock:%@  错误描述:%@",sock,err);
    NSLog(@"断开的sock:%@",self.clientSocket);
    
    self.clientSocket.delegate = nil;
    self.clientSocket = nil;
    self.socketState = DevSocketStateDisconnect;
    [self.connectTimer invalidate];
    if([self.delegate respondsToSelector:@selector(DevSocketDidDisconnect:withError:)]){
        [self.delegate DevSocketDidDisconnect:sock withError:err];
    }
    
}


@end
